<template>
    <div class="exam-container">
        <div class="filter-section">
            <el-tabs v-model="activeName" type="border-card" class="period-container" @tab-click="handleClick">
                <!-- 课程目录 -->
                <el-tab-pane label="课程目录" name="first">
                    <div class="content-wrapper">
                        <div class="video-list">
                            <div v-for="(video, index) in videoList" :key="video.id" class="video-item">
                                <div class="video-info">
                                    <div class="order">{{ index + 1 }}</div>
                                    <div class="thumbnail">
                                        <img :src="video.thumbnailUrl" alt="视频缩略图">
                                        <div class="duration">{{ video.duration }}</div>
                                        <i class="el-icon-video-play play-icon"></i>
                                    </div>
                                    <div class="content">
                                        <h4 class="title">{{ video.name }}</h4>
                                        <div class="meta">
                                            <span class="views"><el-icon>
                                                    <Avatar />
                                                </el-icon>{{ video.teachName }}</span>
                                        </div>
                                        <div class="progress">
                                            <el-progress :percentage="video.flow == 1 ? 100 : video.progress"
                                                :stroke-width="6" :show-text="false" color="#409EFF" />
                                            <span class="progress-text"> {{ video.flow == 1 ? 100 : (video.progress ?? 0).toFixed(1) }}%</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="actions">
                                    <el-button type="primary" icon="video-play" @click="videoPlayer(video)">立即学习
                                    </el-button>
                                </div>
                            </div>
                        </div>
                        <!-- 分页 -->
                        <div class="pagination-wrapper">
                            <el-pagination :current-page="currentPage1" :page-size="pageSize1" :total="total1"
                                @current-change="handleCurrentChange1" @size-change="handleSizeChange1"
                                :page-sizes="[8, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper"
                                :background="true" />
                        </div>
                    </div>
                </el-tab-pane>

                <!-- 课程评价 -->
                <el-tab-pane label="课程评价" name="second">
                    <div class="content-wrapper">
                        <div class="infinite-list-wrapper">
                            <ul class="comment-list" :infinite-scroll-disabled="disabled">
                                <li v-for="(courseEvaluate, index) in courseEvaluateList" :key="courseEvaluate.id"
                                    class="comment-item">
                                    <div class="avatar">
                                        <img style="width: 50px;height: 50px;border-radius: 100%"
                                            :src="serverIp + courseEvaluate.photo"></img>
                                    </div>
                                    <div class="content">
                                        <h4>{{ courseEvaluate.stuname }}</h4>
                                        <p class="comment-text">{{ courseEvaluate.periodFeedback }} </p>
                                    </div>
                                </li>
                            </ul>
                        </div>
                        <!-- 分页 -->
                        <div class="pagination-wrapper">
                            <el-pagination :current-page="currentPage2" :page-size="pageSize2" :total="total2"
                                @current-change="handleCurrentChange2" @size-change="handleSizeChange2"
                                :page-sizes="[8, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper"
                                :background="true" />
                        </div>
                    </div>
                </el-tab-pane>

                <!-- 教师评价 -->
                <el-tab-pane label="教师评价" name="third">
                    <div class="content-wrapper">
                        <!-- 教师评价内容结构类似课程评价 -->
                        <div class="infinite-list-wrapper">
                            <ul class="comment-list" :infinite-scroll-disabled="disabled">
                                <li v-for="(teacherEvaluate, index) in teacherEvaluateList" :key="teacherEvaluate.id"
                                    class="comment-item">
                                    <div class="avatar">
                                        <img style="width: 50px;height: 50px;border-radius: 100%"
                                            :src="serverIp + teacherEvaluate.photo"></img>
                                    </div>
                                    <div class="content">
                                        <h4>{{ teacherEvaluate.stuname }}</h4>
                                        <p class="comment-text">{{ teacherEvaluate.evaluate }} </p>
                                    </div>
                                </li>
                            </ul>
                        </div>
                        <!-- 分页 -->
                        <div class="pagination-wrapper">
                            <el-pagination :current-page="currentPage3" :page-size="pageSize3" :total="total3"
                                @current-change="handleCurrentChange3" @size-change="handleSizeChange3"
                                :page-sizes="[8, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper"
                                :background="true" />
                        </div>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>

    <el-dialog :close-on-click-modal="false" title="上传照片" v-model="dialogVisible" :style="dialogStyle1" @close="closeCamera">
        <el-form label-position="top" :inline="true">
            <el-form-item>
                <el-button @click="uploadImage()" type="primary">上传照片</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="签名" v-model="dialogVisible1" :style="dialogStyle1">
        <div style="width: 100%;text-align: left">
            <Signature :resultImg="resultImg" @updateSignImg="updateSignImg" />
        </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" v-model="dialogVideoVisible" title="视频播放" @close="closedialogVisible"
        @closed="handleDialogClosed" :style="dialogStyle">
        <div class="video-player" ref="videoPlayerContainer">
            <div class="video-placeholder" @mouseenter="showControls = true" @mouseleave="startControlsTimer">
                <video :disablepictureinpicture="true" @contextmenu="contextmenu" class="videoPlayer"
                    :src="serverIp + videoUrl" @play="playVideo" @pause="pauseVideo"
                    @timeupdate="updatePlaybackPosition" @ended="markVideoAsWatched" @loadedmetadata="updateDuration"
                    ref="videoPlayer" type="video/mp4">
                </video>

                <!-- 自定义控制条 -->
                <div class="custom-controls" :class="{ hidden: !showControls }">
                    <button class="play-pause-btn" @click="togglePlay">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="white">
                            <path v-if="isPlaying" d="M6 19h4V5H6v14zm8-14v14h4V5h-4z" />
                            <path v-else d="M8 5v14l11-7z" />
                        </svg>
                    </button>
                    <div class="time-display">
                        {{ formatTime(currentTime) }} / {{ formatTime(duration) }}
                    </div>
                    <div class="progress-container" :class="{ disabled: currentPeriod && currentPeriod.flow === 0 }"
                        @click="seekVideo" @mousemove="updateHoverTime">
                        <div class="progress-bar" :style="{ width: progressPercentage + '%' }">
                            <div class="progress-handle"></div>
                        </div>
                    </div>
                    <div class="volume-control">
                        <button class="volume-btn" @click="toggleMute">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="white">
                                <path v-if="isMuted"
                                    d="M16.5 12A4.5 4.5 0 0014 7.97v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51A8.796 8.796 0 0021 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06a8.99 8.99 0 003.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z" />
                                <path v-else-if="volumeLevel <= 0.5"
                                    d="M18.5 12c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM5 9v6h4l5 5V4L9 9H5z" />
                                <path v-else
                                    d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z" />
                            </svg>
                        </button>
                        <div class="volume-slider" @click="setVolume">
                            <div class="volume-level" :style="{ width: volumePercentage + '%' }"></div>
                        </div>
                    </div>
                    <button class="fullscreen-btn" @click="toggleFullscreen">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="white">
                            <path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z" />
                        </svg>
                    </button>
                </div>
            </div>
        </div>
    </el-dialog>
</template>

<script>
import { ElAvatar, ElEmpty, ElIcon } from 'element-plus'
import TakePhotos from '~/components/TakePhotos.vue';
import Signature from '~/components/Signature.vue';
import request from "~/utils/request.js";
import { serverIp } from "~/utils/config.js";
export default {
    name: 'Period',
    components: {
        ElAvatar,
        ElEmpty,
        ElIcon,
        TakePhotos,
        Signature
    },
    data() {
        return {
            windowWidth: window.innerWidth,
            serverIp: serverIp,
            dialogVisible: false,
            dialogVisible1: false,
            dialogVideoVisible: false,

            // 签名相关数据
            trainSign: {
                photo: '', // 照片
                url: '', // 签名
                stuId: this.$store.state.user.id, // 学员ID
                periodId: '', // 课时ID
                flow: 0, // 完成进度
            },
            showCamera: false, // 控制摄像头组件的显隐
            currentVideo: null, // 当前播放的视频信息
            courseId: "",    // 从路由参数中获取课程ID

            activeName: 'first',
            count: 10,
            loading: false,
            totalVideos: 100,
            userId: this.$store.state.user.id,
            videoList: [],
            courseEvaluateList: [],
            teacherEvaluateList: [],
            // 课程目录分页数据
            currentPage1: 1,
            pageSize1: 8,
            total1: 40,

            // 课程评价分页数据
            currentPage2: 1,
            pageSize2: 8,
            total2: 20,

            // 教师评价分页数据
            currentPage3: 1,
            pageSize3: 8,
            total3: 0,

            videoUrl: '',
            currentPeriod: null,
            watchRecord: null,
            currentPosition: 0,
            currentVideoId: null,
            isPlaying: false,
            showProgress: true, // 控制是否显示进度条
            previousVideoId: null, // 记录上一个视频ID
            previousVideoPosition: 0, // 记录上一个视频位置
            // 自定义控制相关
            showControls: true,
            controlsTimer: null,
            currentTime: 0,
            duration: 0,
            volumeLevel: 0.7,
            isMuted: false,
            hoverTime: 0,
            hoverPosition: 0,
            lastSavedSec: -1 // 记录上次保存的秒数
        }
    },
    computed: {
        progressPercentage() {
            if (this.duration === 0) return 0;
            return (this.currentTime / this.duration) * 100;
        },
        volumePercentage() {
            return this.volumeLevel * 100;
        },
        dialogStyle() {
            return this.windowWidth <= 768 ? { width: '90%' } : { width: '50%' };
        },
        dialogStyle1() {
            return this.windowWidth <= 768 ? { width: '90%' } : { width: '360px' };
        }
    },
    mounted() {
        window.addEventListener('resize', this.handleResize);
    },
    beforeUnmount() {
        window.removeEventListener('resize', this.handleResize);
    },
    activated() {
        this.load()
    },
    beforeDestroy() {
        this.saveBeforeLeave();
    },
    methods: {
        handleResize() {
            this.windowWidth = window.innerWidth;
        },
        contextmenu(e) {
            e.returnValue = false
        },
        // 格式化时间（秒转时分秒）
        formatTime(seconds) {
            if (seconds == null || seconds === '' || isNaN(seconds)) return '00:00';
            seconds = parseInt(seconds);
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const secs = seconds % 60;

            if (hours > 0) {
                return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
            } else {
                return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
            }
        },
        // 切换视频前保存当前进度
        async switchVideo(newVideo) {
            // 暂停当前视频
            if (this.$refs.videoPlayer && !this.$refs.videoPlayer.paused) {
                this.$refs.videoPlayer.pause();
            }

            // 保存当前视频进度
            if (this.currentVideoId) {
                // 确保获取最新进度
                this.currentPosition = this.$refs.videoPlayer.currentTime;
                await this.savePlaybackPosition();
            }
            // 切换到新视频
            this.selectVideo(newVideo);
        },

        // 选择视频
        async selectVideo(row) {
            this.dialogVideoVisible = true;
            // 重置播放状态
            this.isPlaying = false;

            // 重置视频时长和进度
            this.duration = 0;
            this.currentTime = 0;

            // 重置保存计时
            this.lastSavedSec = -1;

            // 记录上一个视频信息
            if (this.currentVideoId) {
                this.previousVideoId = this.currentVideoId;
                this.previousVideoPosition = this.$refs.vueMiniPlayer?.currentTime || 0;
            }

            this.currentPeriod = row;
            this.videoUrl = row.url;
            this.currentVideoId = row.id;
            this.currentLogId = null;
            this.showProgress = row.flow !== 0; // 根据flow状态决定是否显示进度条

            // 获取观看记录
            try {
                const res = await request.get("/train-sign/findAllByUserId?userId=" +
                    this.userId + "&periodId=" + row.id);

                if (res.code === '200' && res.data) {
                    this.watchRecord = res.data;
                    this.currentLogId = res.data.id;
                    this.currentPosition = res.data.time || 0;
                } else {
                    this.watchRecord = { time: 0, status: 0 };
                    this.currentPosition = 0;
                }
            } catch (error) {
                console.error('获取观看记录失败', error);
                this.watchRecord = { time: 0, status: 0 };
                this.currentPosition = 0;
            }

            // 设置自动跳转历史播放点
            this.$nextTick(() => {
                setTimeout(() => {
                    if (this.watchRecord && this.watchRecord.time) {
                        this.$refs.videoPlayer.currentTime = this.watchRecord.time;
                        this.currentTime = this.watchRecord.time;
                    }
                }, 500);
            });
        },

        // 更新视频时长
        updateDuration(event) {
            this.duration = event.target.duration;
        },

        // 播放/暂停切换
        togglePlay() {
            if (this.$refs.videoPlayer.paused) {
                this.$refs.videoPlayer.play();
            } else {
                this.$refs.videoPlayer.pause();
            }
        },

        // 播放视频
        playVideo() {
            this.isPlaying = true;
            this.startControlsTimer();
        },

        // 暂停视频
        pauseVideo() {
            this.isPlaying = false;
            this.showControls = true;
            clearTimeout(this.controlsTimer);
            if (this.$refs.videoPlayer) {
                this.$refs.videoPlayer.pause();
            }
        },
        // 更新播放位置
        updatePlaybackPosition(event) {
            this.currentTime = event.target.currentTime;

            // 确保每次更新时都获取最新时长
            if (this.duration !== event.target.duration) {
                this.duration = event.target.duration;
            }

            if (!this.isPlaying) return;

            // 获取当前整数秒
            const currentSec = Math.floor(this.currentTime);
            // 每10秒保存一次，并且确保当前秒与上一次保存的秒不同（避免同一秒内多次保存）
            if (currentSec % 10 === 0 && currentSec !== this.lastSavedSec) {
                this.savePlaybackPosition();
                this.lastSavedSec = currentSec; // 更新上一次保存的时间
            }
        },

        // 切换静音
        toggleMute() {
            this.isMuted = !this.isMuted;
            this.$refs.videoPlayer.muted = this.isMuted;
        },

        // 设置音量
        setVolume(event) {
            const volumeSlider = event.currentTarget;
            const rect = volumeSlider.getBoundingClientRect();
            const position = (event.clientX - rect.left) / rect.width;
            this.volumeLevel = Math.max(0, Math.min(1, position));
            this.$refs.videoPlayer.volume = this.volumeLevel;
            this.isMuted = this.volumeLevel === 0;
        },

        // 跳转视频进度
        seekVideo(event) {
            if (this.currentPeriod && this.currentPeriod.flow === 0) return;

            const progressContainer = event.currentTarget;
            const rect = progressContainer.getBoundingClientRect();
            const position = (event.clientX - rect.left) / rect.width;
            const newTime = position * this.duration;

            this.$refs.videoPlayer.currentTime = newTime;
            this.currentTime = newTime;
        },

        closedialogVisible() {
            this.pauseVideo();
            this.saveBeforeLeave();
            this.dialogVideoVisible = false;
            this.$refs.videoPlayer.load();
        },

        handleDialogClosed() {
            if (this.$refs.videoPlayer) {
                this.$refs.videoPlayer.pause();
            }
            this.isPlaying = false;
        },

        updateHoverTime(event) {
            const progressContainer = event.currentTarget;
            const rect = progressContainer.getBoundingClientRect();
            this.hoverPosition = (event.clientX - rect.left) / rect.width;
            this.hoverTime = this.hoverPosition * this.duration;
        },

        toggleFullscreen() {
            // 使用ref获取容器元素
            const player = this.$refs.videoPlayerContainer;

            if (!document.fullscreenElement) {
                if (player.requestFullscreen) {
                    player.requestFullscreen();
                } else if (player.mozRequestFullScreen) {
                    player.mozRequestFullScreen();
                } else if (player.webkitRequestFullscreen) {
                    player.webkitRequestFullscreen();
                } else if (player.msRequestFullscreen) {
                    player.msRequestFullscreen();
                }
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                }
            }
        },

        // 控制条自动隐藏
        startControlsTimer() {
            clearTimeout(this.controlsTimer);
            this.controlsTimer = setTimeout(() => {
                if (this.isPlaying) {
                    this.showControls = false;
                }
            }, 3000);
        },

        async savePlaybackPosition(isEnded = false) {
            if (!this.currentVideoId) return;

            // 获取当前播放时间
            const currentTime = this.$refs.videoPlayer?.currentTime || 0;

            // 构建保存数据
            const saveData = {
                id: this.currentLogId,
                periodId: this.currentVideoId,
                stuId: this.userId,
                time: isEnded ? this.duration : currentTime,
                flow: isEnded ? 1 : 0
            };

            // 如果之前已看完，只更新时间不改变状态
            if (this.watchRecord && this.watchRecord.status === 1) {
                saveData.flow = 1;
            }

            try {
                const res = await request.post('/train-sign/edit', saveData);
                if (res.code === '200') {
                    // 更新本地记录
                    this.watchRecord = res.data;
                    this.currentLogId = res.data.id;
                    this.currentPosition = saveData.time;

                    // 如果视频结束，标记为已完成
                    if (isEnded) {
                        this.currentPeriod.flow = 1;
                        // 更新列表中的状态
                        const periodIndex = this.periods.findIndex(p => p.id === this.currentVideoId);
                        if (periodIndex !== -1) {
                            this.periods[periodIndex].flow = 1;
                        }
                    }
                } else {
                    console.error('保存播放位置失败:', res.msg);
                }
            } catch (error) {
                console.error('保存播放位置失败:', error);
            }
        },

        // 离开页面时保存进度
        async saveBeforeLeave() {
            if (this.$refs.videoPlayer && this.currentVideoId) {
                // 确保获取最新进度
                this.currentPosition = this.$refs.videoPlayer.currentTime;
                await this.savePlaybackPosition();
            }
        },

        // 标记视频为已看完
        markVideoAsWatched() {
            if (this.currentVideoId) {
                this.savePlaybackPosition(true);
            }
        },


        load() {
            this.courseId = this.$route.query.courseId;
            if (this.activeName === 'first') {
                request.get("/period/stuFindPeriod", {
                    params: {
                        pageNum: this.currentPage1,
                        pageSize: this.pageSize1,
                        courseId: this.courseId,
                        userId: this.userId,
                    }
                }).then(res => {
                    if (res.code === "200") {
                        console.log(res.data.records)
                        this.videoList = res.data.records;
                        this.total1 = res.data.total;
                    }
                })
            } else if (this.activeName === 'second') {
                request.get("/stu-feedback/stuFindCourseEvaluation", {
                    params: {
                        pageNum: this.currentPage2,
                        pageSize: this.pageSize2,
                        courseId: this.courseId,
                    }
                }).then(res => {
                    if (res.code === "200") {
                        this.courseEvaluateList = res.data.records;
                        this.total2 = res.data.total;
                    }
                })
            } else if (this.activeName === 'third') {
                request.get("/teach-evaluate/stuFindTeacherEvaluation", {
                    params: {
                        pageNum: this.currentPage3,
                        pageSize: this.pageSize3,
                    }
                }).then(res => {
                    if (res.code === "200") {
                        this.teacherEvaluateList = res.data.records;
                        this.total3 = res.data.total;
                    }
                })
            }
        },
        handleClick(tab) {
            this.activeName = tab.props.name;

            if (this.activeName === 'first') {
                request.get("/period/stuFindPeriod", {
                    params: {
                        pageNum: this.currentPage1,
                        pageSize: this.pageSize1,
                        courseId: this.courseId,
                        userId: this.userId,
                    }
                }).then(res => {
                    if (res.code === "200") {
                        this.videoList = res.data.records;
                        this.total1 = res.data.total;
                    }
                })
            } else if (this.activeName === 'second') {
                request.get("/stu-feedback/stuFindCourseEvaluation", {
                    params: {
                        pageNum: this.currentPage2,
                        pageSize: this.pageSize2,
                        courseId: this.courseId,
                    }
                }).then(res => {
                    if (res.code === "200") {
                        this.courseEvaluateList = res.data.records;
                        this.total2 = res.data.total;
                    }
                })
            } else if (this.activeName === 'third') {
                request.get("/teach-evaluate/stuFindTeacherEvaluation", {
                    params: {
                        pageNum: this.currentPage3,
                        pageSize: this.pageSize3,
                    }
                }).then(res => {
                    if (res.code === "200") {
                        this.teacherEvaluateList = res.data.records;
                        this.total3 = res.data.total;
                    }
                })
            }
        },
        avatarUrl(i) {
            return `https://randomuser.me/api/portraits/${i % 2 === 0 ? 'women' : 'men'
                }/${i % 10}.jpg`
        },
        // 课程目录分页方法
        handleCurrentChange1(val) {
            this.currentPage1 = val;
            // 加载课程目录数据
            this.load()
        },
        handleSizeChange1(val) {
            this.pageSize1 = val;
            // 加载课程目录数据
            this.load()
        },

        // 课程评价分页方法
        handleCurrentChange2(val) {
            this.currentPage2 = val;
            // 加载评价数据
            this.load()
        },
        handleSizeChange2(val) {
            this.pageSize2 = val;
            // 加载评价数据
            this.load()
        },

        // 教师评价分页方法
        handleCurrentChange3(val) {
            this.currentPage3 = val;
            // 加载教师评价数据
            this.load()
        },
        handleSizeChange3(val) {
            this.pageSize3 = val;
            // 加载教师评价数据
            this.load()
        },

        async videoPlayer(video) {
            try {
                this.trainSign.periodId = video.id;
                this.currentVideo = video;
                // 检查是否已经完成签到
                const res = await request.get("/train-sign/stuFindIsTrainSign", {
                    params: {
                        periodId: video.id,
                        stuId: this.$store.state.user.id,
                    }
                });

                // 检查响应状态和数据
                if (res.code === "200" && res.data.isTrainSign === true) {
                    this.selectVideo(video)
                    return;
                }

                this.dialogVisible = true;
                this.currentVideo = video;
                this.showCamera = true; // 显示摄像头组件
                // 其他视频播放逻辑（如打开视频播放器）
            } catch (error) {
                console.error('签到检查失败:', error);
            }
        },
        // videoLinePlay(row){
        //     this.videoUrl=row.url;
        //     this.dialogVideoVisible=true;
        // },
        // handleVideoEnd() {
        //     if (this.currentVideo) {
        //         this.videoPlayerFinish(this.currentVideo)
        //     }
        // },
        // videoPlayerFinish(row) {
        //     //视频观看完后的操作
        //     console.log('视频播放完成:', row.id)
        //     // 调用接口上传
        //     request.get("/train-sign/stuUpdateTrainSignFlow", {
        //         params: {
        //             periodId: row.id,
        //             stuId: this.$store.state.user.id,
        //         }
        //     })
        // },

        // 上传图片
        uploadImage() {
            // 创建文件选择输入
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = 'image/*';

            input.onchange = async (e) => {
                const file = e.target.files[0];
                if (!file) return;
                // 上传图片到服务器
                // 创建FormData并添加文件
                const formData = new FormData()
                formData.append('file', file) // 字段名必须与接口参数名一致

                // 发送请求（根据实际请求库调整）
                request.post("/files/upload", formData).then(res => {
                    if (res !== null && res !== "") {
                        this.$message.success('上传成功');
                        this.handlePhotoUpload(res)
                    }
                }).catch(err => {
                    console.error('上传失败:', err)
                })
            };

            // 触发文件选择对话框
            input.click();
        },
        // 处理拍照完成后的回调
        handlePhotoUpload(url) {
            console.log('照片上传成功:', url);
            this.trainSign.photo = `/api/file/download/${url}`
            this.dialogVisible = false
            this.dialogVisible1 = true
        },
        handleCameraClose() {
            // 重置摄像头但不隐藏组件
            if (this.$refs.takePhotosRef) {
                this.$refs.takePhotosRef.closeCamera();
            }
        },
        updateSignImg(sign) {
            console.log(sign)
            this.trainSign.url = `${sign}`
            // 调用接口上传
            request.post("/train-sign/edit", this.trainSign).then(res => {
                if (res.code === "200") {
                    this.$message.success("上传成功")
                }
            })

            this.dialogVisible1 = false;
        },
        closeCamera() {
            if (this.$refs.takePhotosRef) {
                this.$refs.takePhotosRef.stopNavigator();
            }
            this.showCamera = false;
        },
    }
}
</script>

<style scoped>
    /* 原有Web端样式保持不变，只添加移动端适配 */

    .exam-container {
        display: flex;
        flex-direction: column;
    }

    .filter-section {
        flex: 1;
        display: flex;
        height: 45vh;
        flex-direction: column;
        overflow: hidden;
    }

    .period-container {
        flex: 1;
        display: flex;
        margin: 0;
        box-shadow: none;
        border-radius: 0;
    }

    /* 分页吸底容器 */
    .pagination-wrapper {
        position: sticky;
        bottom: 0;
        background: white;
        z-index: 2;
        padding: 16px 0;
        border-top: 1px solid #ebeef5;
        margin-top: auto;
    }

    /* 内容容器高度控制 */
    .content-wrapper {
        height: 100%;
        display: flex;
        flex-direction: column;
        padding: 0 20px;
    }

    /* 列表区域自动滚动 */
    .video-list,
    .comment-list {
        flex: 1;
        overflow-y: auto;
        padding: 20px 0;
    }

    /* 移除无限滚动相关样式 */
    .infinite-list-wrapper {
        height: auto !important;
    }

    /* 固定标签标题 */
    ::v-deep .el-tabs__header {
        position: sticky;
        top: 0;
        background: white;
        z-index: 3;
        margin: 0;
    }

    /* 视频列表滚动区域 */
    ::v-deep .el-tabs__content {
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow-y: auto;
        padding: 0 !important;
    }

    /* 分页样式 */
    .el-pagination {
        display: flex;
        position: sticky;
        top: 0;
        flex: 1;
        justify-content: center;
        margin-top: 24px !important;
    }

    .content-wrapper {
        padding: 20px;
    }

    .video-item {
        background: #fff;
        border-radius: 8px;
        padding: 16px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        transition: all 0.3s;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
    }

    .video-item:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
    }

    .video-info {
        display: flex;
        align-items: center;
        flex: 1;
        gap: 16px;
    }

    .order {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: #409EFF;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: bold;
    }

    .thumbnail {
        position: relative;
        width: 240px;
        height: 135px;
        border-radius: 4px;
        overflow: hidden;
        flex-shrink: 0;
    }

    .thumbnail img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .duration {
        position: absolute;
        right: 8px;
        bottom: 8px;
        background: rgba(0, 0, 0, 0.7);
        color: white;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;
    }

    .play-icon {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 36px;
        color: rgba(255, 255, 255, 0.9);
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    }

    .content {
        flex: 1;
    }

    .title {
        margin: 0 0 8px;
        font-size: 16px;
        color: #303133;
    }

    .meta {
        display: flex;
        gap: 20px;
        margin-bottom: 12px;
        color: #909399;
        font-size: 13px;
    }

    .progress {
        width: 80%;
    }

    .progress-text {
        display: block;
        margin-top: 4px;
        color: #409EFF;
        font-size: 12px;
    }

    .actions {
        flex-shrink: 0;
        display: flex;
        flex-direction: column;
        gap: 8px;
    }

    .pagination {
        margin-top: 24px;
    }

    .period-container {
        margin: 20px;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    }

    .content-wrapper {
        padding: 20px;
        min-height: 500px;
    }

    /* 课程目录布局 */
    .course-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
        gap: 16px;
        margin-bottom: 20px;
    }

    .course-card {
        background: #fff;
        border-radius: 8px;
        padding: 16px;
        transition: all 0.3s;
        border: 1px solid #ebeef5;
    }

    .course-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .card-content {
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .card-content i {
        font-size: 24px;
        color: #409eff;
    }

    .comment-item {
        display: flex;
        gap: 16px;
        padding: 16px;
        margin-bottom: 12px;
        background: #fff;
        border-radius: 8px;
        transition: all 0.2s;
        border: 1px solid #ebeef5;
    }

    .comment-item:hover {
        background: #f8f9fc;
    }

    .comment-item .content h4 {
        margin: 0 0 8px 0;
        color: #303133;
    }

    .comment-item .content p {
        margin: 0;
        color: #606266;
        line-height: 1.5;
    }

    .loading-status {
        text-align: center;
        padding: 20px;
        color: #909399;
    }

    .loading-text i {
        margin-right: 8px;
    }

    .pagination {
        margin-top: 24px;
        display: flex;
        justify-content: center;
    }

    /* 新增拍照按钮样式 */
    .camera-container button {
        background: #409EFF;
        color: white;
        border: none;
        padding: 12px 24px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
        transition: all 0.3s;
    }

    .camera-container button:hover {
        background: #66b1ff;
    }

    .video-preview {
        width: 80%;
        height: 70vh;
        margin: 20px 0;
        background: black;
    }

    .video-player {
        position: relative;
        background: linear-gradient(45deg, #2c3e50, #1a1a2e);
        height: 0;
        padding-bottom: 56.25%; /* 16:9 宽高比 */
    }

    .video-placeholder {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: white;
    }

    .video-placeholder i {
        font-size: 80px;
        margin-bottom: 20px;
        color: rgba(255, 255, 255, 0.7);
    }

    .video-placeholder h2 {
        font-size: 28px;
        font-weight: 500;
        margin-bottom: 10px;
    }

    .video-placeholder p {
        font-size: 16px;
        opacity: 0.8;
        max-width: 80%;
        text-align: center;
        line-height: 1.6;
    }

    .videoPlayer {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: contain;
    }

    .custom-controls {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        background: rgba(0, 0, 0, 0.7);
        padding: 10px 15px;
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        transition: opacity 0.3s;
        z-index: 10;
    }

    .custom-controls.hidden {
        opacity: 0;
        pointer-events: none;
    }

    .play-pause-btn {
        background: none;
        border: none;
        color: white;
        font-size: 20px;
        cursor: pointer;
        margin-right: 15px;
        width: 30px;
        height: 30px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .time-display {
        color: white;
        font-size: 14px;
        margin-right: 15px;
        min-width: 100px;
    }

    .progress-container {
        flex: 1;
        height: 5px;
        background: #555;
        border-radius: 3px;
        position: relative;
        cursor: pointer;
        margin: 0 15px;
    }

    /* 添加禁用状态样式 */
    .progress-container.disabled {
        opacity: 0.6;
        cursor: not-allowed;
        pointer-events: none;
    }

    .progress-bar {
        height: 100%;
        background: #c7000b;
        border-radius: 3px;
        width: 0%;
        position: relative;
    }

    .progress-container.disabled .progress-bar {
        background: #888;
    }

    .progress-handle {
        position: absolute;
        top: 50%;
        right: -8px;
        width: 16px;
        height: 16px;
        background: white;
        border-radius: 50%;
        transform: translateY(-50%);
        box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
        display: none;
    }

    .progress-container:hover .progress-handle {
        display: block;
    }

    .volume-control {
        display: flex;
        align-items: center;
        margin-right: 15px;
    }

    .volume-btn {
        background: none;
        border: none;
        color: white;
        font-size: 18px;
        cursor: pointer;
        margin-right: 5px;
    }

    .volume-slider {
        width: 80px;
        height: 5px;
        background: #555;
        border-radius: 3px;
        position: relative;
        cursor: pointer;
    }

    .volume-level {
        height: 100%;
        background: white;
        border-radius: 3px;
        width: 80%;
    }

    .fullscreen-btn {
        background: none;
        border: none;
        color: white;
        font-size: 18px;
        cursor: pointer;
    }

    .video-info {
        padding: 20px;
    }

    .video-info h3 {
        font-size: 22px;
        color: #c7000b;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 2px solid #eee;
        display: flex;
        align-items: center;
    }

    .video-info p {
        line-height: 1.8;
        color: #444;
        font-size: 16px;
        display: flex;
        align-items: center;
    }

    /* 添加评论内容自动换行样式 */
    .comment-text {
        white-space: pre-wrap;
        word-wrap: break-word;
        overflow-wrap: break-word;
        word-break: break-word;
        line-height: 1.5;
        margin: 0;
    }

    /* 确保评论容器有适当宽度限制 */
    .comment-item .content {
        max-width: calc(100% - 70px);
    }

    .el-dialog-image {
        height: 100px;
        width: 200px;
        margin-top: 10px;
        margin-right: 10px;
        border: 1px solid #ccc;
        display: flex;
        align-items: center;
        justify-content: center;
    }
    /* ========== 移动端适配 ========== */
    @media (max-width: 768px) {
        .exam-container {
            height: auto;
            min-height: calc(100vh - 80px);
            padding: 10px;
        }

        .filter-section {
            height: auto;
            min-height: 50vh;
        }

        .period-container {
            margin: 0;
            border-radius: 0;
            box-shadow: none;
        }

        .content-wrapper {
            padding: 10px;
        }

        /* 视频列表项移动端适配 */
        .video-item {
            flex-direction: column;
            align-items: flex-start;
            padding: 12px;
            margin-bottom: 12px;
        }

        .video-info {
            width: 100%;
            flex-direction: column;
            align-items: flex-start;
            gap: 12px;
        }

        .thumbnail {
            width: 100%;
            height: auto;
            aspect-ratio: 16/9;
        }

        .order {
            align-self: flex-start;
        }

        .content {
            width: 100%;
        }

        .title {
            font-size: 16px;
            margin-bottom: 6px;
        }

        .meta {
            font-size: 12px;
            margin-bottom: 8px;
        }

        .progress {
            width: 100%;
        }

        .actions {
            width: 100%;
            margin-top: 12px;
            flex-direction: row;
            justify-content: flex-end;
        }

        /* 评论列表移动端适配 */
        .comment-item {
            padding: 12px;
            margin-bottom: 10px;
        }

        .comment-item .avatar img {
            width: 40px;
            height: 40px;
        }

        .comment-item .content {
            max-width: calc(100% - 56px);
        }

        .comment-item .content h4 {
            font-size: 14px;
            margin-bottom: 6px;
        }

        .comment-item .content p {
            font-size: 13px;
        }


        .pagination-wrapper {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            z-index: 900;
            padding: 12px 10px;
            border-top: 1px solid #ebeef5;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
        }

        /* 为内容区域添加底部内边距，避免被分页遮挡 */
        .content-wrapper {
            padding-bottom: 70px !important;
        }

        .video-list,
        .comment-list {
            padding-bottom: 20px;
        }

        /* 分页样式 */
        .el-pagination {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
        }

        .el-pagination__total {
            order: 1;
            width: 50%;
            text-align: left;
        }

        .el-pagination__sizes {
            order: 2;
            width: 50%;
            text-align: right;
        }

        .el-pagination .btn-prev,
        .el-pagination .el-pager,
        .el-pagination .btn-next {
            order: 3;
            width: 100%;
            text-align: center;
            margin: 10px 0;
        }

        .el-pagination .el-pagination__jump {
            order: 4;
            width: 100%;
            text-align: center;
        }

        .video-player {
            width: 90%;
            position: relative;
            background: linear-gradient(45deg, #2c3e50, #1a1a2e);
            height: 0;
            /*padding-bottom: 56.25%; !* 16:9 宽高比 *!*/
        }

        ::v-deep .el-dialog__body {
            padding: 15px;
            max-height: calc(90vh - 100px);
            overflow: hidden;
        }

        .video-player {
            padding-bottom: 56.25%; /* 保持16:9比例 */
            height: 0;
        }

        .video-placeholder {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }

        .videoPlayer {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }

        /* 移动端控制条优化 */
        .custom-controls {
            padding: 8px 10px;
            height: 50px;
        }

        .play-pause-btn {
            width: 24px;
            height: 24px;
            margin-right: 10px;
        }

        .time-display {
            min-width: 70px;
            font-size: 11px;
            margin-right: 8px;
        }

        .progress-container {
            margin: 0 8px;
            height: 4px;
        }

        .volume-control {
            margin-right: 8px;
        }

        .volume-slider {
            width: 40px;
            height: 4px;
        }

        .fullscreen-btn {
            width: 24px;
            height: 24px;
        }





        /* 标签页移动端适配 */
        ::v-deep .el-tabs__nav {
            flex-wrap: wrap;
        }

        ::v-deep .el-tabs__item {
            padding: 0 12px;
            font-size: 14px;
        }

        /* 按钮移动端适配 */
        .el-button {
            padding: 8px 12px;
            font-size: 13px;
        }

        /* 缩略图移动端适配 */
        .play-icon {
            font-size: 28px;
        }

        .duration {
            font-size: 11px;
            padding: 1px 6px;
        }
    }
</style>
